package ru.athena.runTool;

import java.io.ByteArrayOutputStream;
import java.io.FilterOutputStream;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;

public class LogWriter extends PrintStream {

	private static StreamToBufferCapturer streamCapturer_ = null;
	private static PrintStream printStream_ = null;
	
	public static PrintStream out() {
		
		if (printStream_ == null) {
			// capture stream to buffer
			printStream_ = new PrintStream( getBuffer() );			
		}
		return printStream_;		
	}

	/**
	 * 
	 * @return text, exists in log buffer. 
	 * 	After extract, text have been erased
	 */
	public static String extractText() {
		return getBuffer().extractText();
	}
	
	private LogWriter(OutputStream out) {
		super(out);
	}
	
	/**
	 * 
	 */
	private static StreamToBufferCapturer getBuffer() {
		if ( streamCapturer_ == null) { 
			streamCapturer_ = 
				new StreamToBufferCapturer( 
					new ByteArrayOutputStream());
		}
		return streamCapturer_;
	}
	
    private static class StreamToBufferCapturer extends FilterOutputStream {
    	private StringBuilder buffer_ = new StringBuilder();
    	
        public StreamToBufferCapturer(OutputStream stream) {
           super(stream);
        }

        public void write(byte b[])  {
           buffer_.append( new String(b) );
        }

        public void write(byte b[], int off, int len) {
           buffer_.append( new String(b , off , len) );        	
        }
        
        public String getText() {
        	return buffer_.toString();
        }
        
        public String extractText() {
        	String text = getText();
        	clear();
        	return text;
        }

        public void clear() {
        	buffer_  = new StringBuilder("");
        }
    }		

}
